<template>
    <div class="page-employee_sales_data">
        <div class="main">
            <div class="header">
                <ZbSelect v-model="selectedDateType" type="mini" :options="dateTypeOptions" :hasBr="true" default-br="#101010" default-color="#101010" selected-color="#FFFFFF" selected-br="#288DF8" selected-bg="#288DF8" class="nice" />
            </div>
            <SearchBar v-model="tempSearch" placeholder="搜索" @search="onClickSearch" />
            <div class="picker-box clearfix">
                <SelectA v-if="shopSelectVisible" v-model="selectedShops" :options="shopList" />
                <!-- <TimePicker1  :inner-class="fr" v-model="pickerTime" /> -->
                <TimePicker1 :defaultStartDate="startDate" @search="onClickTimeSearch"/>
            </div>
            <div class="order-wrap" v-if="userDataList.length">
                <DetailCard v-for="(item, index) in userDataList"
                    :key="index"
                    :identity="titleMap[level]"
                    :level="level"
                    :start="startDate"
                    :end="endDate"
                    :info="item" />

                <ListFooter :loaded="userDataWrap.loaded" :req="userDataWrap.req" />
            </div>
            <ListEmpty v-else />
        </div>
    </div>
</template>

<script lang="ts">
import store from '@/store';
import CommonNav from '@/components/nav/commonNav.vue';
import ZbSelect from '@/components/common/zbSelect.vue';
import SearchInput from '@/components/search/searchInput.vue';
import TimePicker1 from '@/features/manage/timePicker1.vue';
import PeopleSelect from '@/features/manage/peopleSelect.vue';
import DetailCard from '@/features/manage/detailCard.vue';
import SelectA from '@/features/manage/select.vue';
import {
    // currency,
    getUserDataKey,
    getFirstDayOfMonth,
    getFirstDayOfSeason,
    getFirstDayOfYear,
} from '@/lib/utils';
import { Component, Vue, Watch } from 'vue-property-decorator';
import { EMPTY_LIST } from '@/lib/constant';
import SearchBar from '@/module/manage/components/searchBar.vue';

Component.registerHooks([
    'beforeRouteEnter',
]);

@Component({
    name: 'EmployeeSalesData',
    components: {
        CommonNav,
        ZbSelect,
        SearchInput,
        TimePicker1,
        // ManageHeader,
        PeopleSelect,
        DetailCard,
        SelectA,
        SearchBar,
    },
})
export default class EmployeeSalesData extends Vue {
    // todo: 考虑和startDate进行同步
    public selectedDateType: any = '';
    public dateTypeOptions: string[] = [ '月度', '季度', '年度' ];
    public searchKey: any = '';
    public pickerTime: any = '全部';
    public startDate: string | null = null;
    public endDate: string | null = null;
    /** 搜索 */
    public tempSearch = '';
    public search = '';
    public titleMap: any = {
        '1': '返利会员',
        '2': '城市合伙人',
        '3': '商家职工',
    };
    public selectedShops: number[] = [];

    public get level() {
        return this.$route.query.level;
    }
    /** 用户基础信息 */
    public get userBasicInfo() {
        return store.state.user.basicInfo;
    }
    public get userDataListMap() {
        return store.state.manage.userDataListMap;
    }
    public get shopMap() {
        return store.state.shop.shopMap;
    }
    public get allShopList() {
        return store.state.shop.allShopList;
    }
    /** 店铺列表 */
    public get shopList() {
        const identity = this.userBasicInfo.employee_identity;
        if (!identity) {
            return [];
        }
        const allShopList = store.state.shop.allShopList;
        
        if (identity === '平台管理') {
            return allShopList.map((id) => this.shopMap[id]);
        } else {
            return this.userBasicInfo.shop;
        }
    }
    public get shopSelectVisible() {
        const identity = this.userBasicInfo.employee_identity;
        return identity && (identity === '平台管理' || identity === '商家管理');
    }
    public get shopIdArr() {
        // 有选择的店铺
        if (this.selectedShops && this.selectedShops.length) {
            return this.selectedShops;
        } else {
            // 获取所有店铺
            return [];
        }
    }
    public get orderKey() {
        return getUserDataKey({
            search: this.search,
            shopId: this.shopIdArr,
            identity: this.userBasicInfo.employee_identity || null,
            level: this.level,
            start: this.startDate,
            end: this.endDate,
        });
    }
    public get userDataWrap() {
        return this.userDataListMap[this.orderKey] || EMPTY_LIST;
    }
    public get userDataList(): Manage.UserData[] {
        return this.userDataWrap.list;
    }

    @Watch('nav')
    public onNavChange(val: any) {
        this.getDataList(true);
    }
    @Watch('orderKey')
    public onOrderKeyChange(val: any) {
        // console.log('page key', val);
    }
    @Watch('selectedShops')
    public onSelectedShopsChange(val: any) {
        this.getDataList(true);
    }
    @Watch('selectedDateType')
    public onSelectedDateTypeChange(val: any) {
        if (val === '月度') {
            this.startDate = getFirstDayOfMonth(new Date());
        } else if (val === '季度') {
            this.startDate = getFirstDayOfSeason(new Date());
        } else if (val === '年度') {
            this.startDate = getFirstDayOfYear(new Date());
        }
        this.endDate = null;
        this.getDataList(true);
    }
    @Watch('pickerTime')
    public onPickerTimeChange(val: any) {
        if (val === '全部') {
            this.startDate = null;
            this.endDate = null;
        } else {
            this.startDate = val;
            const arr = val.split('-');
            arr[2] = Number(arr[2]) + 1;
            this.endDate = arr.join('-');
        }
        this.getDataList(true);
    }

    public onClickSearch() {
        this.search = this.tempSearch;
        this.getDataList(true);
    }
    public onClickTimeSearch(obj) {
        this.startDate = obj.startDate;
        this.endDate = obj.endDate;
        this.getDataList(true);
    }
    /**
     * 获取数据列表
     */
    public async getDataList(forceUpdate = false) {
        const params = {
            offset: this.userDataList.length,
            count: 10,
            start: this.startDate,
            end: this.endDate,
            level: this.level,
            identity: this.userBasicInfo.employee_identity,
            shopId: this.shopIdArr,
            search: this.search,
        };
        if (forceUpdate) {
            Object.assign(params, {
                offset: 0,
                forceUpdate,
            });
        }
        await store.dispatch('manage/getUserDataList', params);
    }
    public async onReachBottom() {
        this.getDataList();
    }

    public async created() {
        store.commit('utils/startRequest');
        await Promise.all([
            store.dispatch('shop/getAllShopList'),
        ]);
        store.commit('utils/endRequest');

        window.addEventListener('reachbottom', this.onReachBottom);
        window.addEventListener('pulldownrefresh', async () => {
            store.commit('utils/startPulldown');
            this.selectedShops = [];
            await Promise.all([
                store.dispatch('shop/getAllShopList'),
                this.getDataList(true),
            ]);
            store.commit('utils/endPulldown');
        });

        this.getDataList(true);
    }
    public beforeDestroy() {
        window.removeEventListener('reachbottom', this.onReachBottom);
    }
}
</script>

<style lang="less">
@import "../../lib/style/mixins.less";

.page-employee_sales_data {
    min-height: 100%;
    background-color: #f8f8f8;
    .main {
        .header {
            padding: 10px 10px 0;
            display: flex;
            justify-content: flex-end;
            align-items: center;
            .select-btn-box {
                .item {

                }
            }
            .nice{
                width: 39%;
                display: flex;
            }
        }
    }
    .order-wrap {
        padding: 0 12rpx;
        .detail-card {
            margin-bottom: 10px;
            border-radius: 5px;
            .btn-box {
                padding: 0 15px;
                border-top: 1px solid #bbbbbb;
                background-color: #ffffff;
                overflow: hidden;
                .item {
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    margin: 9px 0;
                    .data {
                        display: flex;
                        justify-content: space-between;
                        width: 200px;
                    }
                }
            }
        }
    }
    .picker-box {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 8px 14px;
    }
}

</style>
